<?php
namespace App\Services;

use App\Models\OrderComplain;
use App\Models\Pintuan;
use App\Models\PintuanSpec;
use App\Models\PintuanTuan;
use App\Models\PintuanTuanCJ;
use App\Models\PintuanTuanData;
use App\Models\PintuanTuanMS;
use App\Models\User;
use App\Services\CashierService;
use App\Models\Address;
use App\Models\Order;
use App\Models\OrderGoods;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 *
 * 订单服务层
 *
 * @author shengl@maqu.im
 *
 */
class OrderService extends BaseService {
    /**
     *    获取外部传递过来的商品
     *
     * @param   $user_id    用户id
     * @param   $rec_ids    购物车ids
     * @param   $store_id   店铺id
     * @param   $goods      购物类型 'normal','groupby'
     *    @return    void
     */
    public function getGoodsInfo($user_id,$rec_ids=[],$store_id=1,$goods)
    {
        $return = array(
            'items'     =>  array(),    //商品列表
            'quantity'  =>  0,          //商品总量
            'amount'    =>  0,          //商品总价
//            'weight'   =>  0,
            'store_id'  =>  1,          //所属店铺
            'store_name'=>  '',         //店铺名称
            'type'      =>  null,       //商品类型
            'otype'     =>  'normal',   //订单类型
            'allow_coupon'  => true,    //是否允许使用优惠券
            'discount'  =>  0,          //折扣金额
            'coupon_sn' =>  0,          //优惠券号
            'supplierid'=>  0, 			//供应商id
        );

        switch ($goods)
        {
            case 'groupbuy':
//                /* 团购的商品 */
//                $group_id = Input::get('group_id',0);
//                $user_id  = $user['user_id'];
//                if (!$group_id || !$user_id)
//                {
//                    return false;
//                }
//
//                /* 获取团购记录详细信息 */
//                $model_groupbuy =& m('groupbuy');
//                $groupbuy_info = $model_groupbuy->get(array(
//                    'join'  => 'be_join, belong_store, belong_goods',
//                    'conditions'    => $model_groupbuy->getRealFields("groupbuy_log.user_id={$user_id} AND groupbuy_log.group_id={$group_id} AND groupbuy_log.order_id=0 AND this.state=" . GROUP_FINISHED),
//                    'fields'    => 'store.store_id, store.store_name, goods.goods_id, goods.goods_name, goods.default_image, groupbuy_log.quantity, groupbuy_log.spec_quantity, this.spec_price',
//                ));
//
//                if (empty($groupbuy_info))
//                {
//                    return false;
//                }
//
//                /* 库存信息 */
//                $model_goodsspec = &m('goodsspec');
//                $goodsspec = $model_goodsspec->find('goods_id='. $groupbuy_info['goods_id']);
//
//                /* 获取商品信息 */
//                $spec_quantity = unserialize($groupbuy_info['spec_quantity']);
//                $spec_price    = unserialize($groupbuy_info['spec_price']);
//                $amount = 0;
//                $groupbuy_items = array();
//                $goods_image = empty($groupbuy_info['default_image']) ? Conf::get('default_goods_image') : $groupbuy_info['default_image'];
//                foreach ($spec_quantity as $spec_id => $spec_info)
//                {
//                    $the_price = $spec_price[$spec_id]['price'];
//                    $subtotal = $spec_info['qty'] * $the_price;
//                    $groupbuy_items[] = array(
//                        'goods_id'  => $groupbuy_info['goods_id'],
//                        'goods_name'  => $groupbuy_info['goods_name'],
//                        'spec_id'  => $spec_id,
//                        'specification'  => $spec_info['spec'],
//                        'price'  => $the_price,
//                        'quantity'  => $spec_info['qty'],
//                        'goods_image'  => $goods_image,
//                        'subtotal'  => $subtotal,
//                        'stock' => $goodsspec[$spec_id]['stock'],
//                    );
//                    $amount += $subtotal;
//                }
//
//                $return['items']        =   $groupbuy_items;
//                $return['quantity']     =   $groupbuy_info['quantity'];
//                $return['amount']       =   $amount;
//                $return['store_id']     =   $groupbuy_info['store_id'];
//                $return['store_name']   =   $groupbuy_info['store_name'];
//                $return['type']         =   'material';
//                $return['otype']        =   'groupbuy';
//                $return['allow_coupon'] =   false;
                break;
            default:
                /* 从购物车中取商品 */
                $cashierService = new CashierService();
                $cart = $cashierService->getGoodsByCart($user_id,$store_id,$rec_ids);
                if (empty($cart['goods']))
                {
                    return false;
                }

                $return['items']        =   $cart['goods'];
                $return['quantity'] = $cart['total_store']['quantity'];                      //商品总量
                $return['amount']   = $cart['total_store']['goods_amount'];    //商品总价
                $return['store_id']     =   $cart['store_info']['store_id'];
                $return['store_name']   =   $cart['store_info']['store_name'];
                $return['type']         =   'material';
                $return['otype']        =   'normal';
                break;
        }

        return $return;
    }

    /**
     *    立即购买商品信息
     *
     * @param   $spec_id 商品规格id
     * @param   $quantity 商品数量
     * @return    void
     */
    public function getSingleGoodsInfo($spec_id,$quantity=1)
    {
        $return = array(
            'items'     =>  array(),    //商品列表
            'quantity'  =>  $quantity,          //商品总量
            'amount'    =>  0,          //商品总价
//            'weight'   =>  0,
            'store_id'  =>  0,          //所属店铺
            'store_name'=>  '',         //店铺名称
            'type'      =>  null,       //商品类型
            'otype'     =>  'normal',   //订单类型
            'allow_coupon'  => true,    //是否允许使用优惠券
            'discount'  =>  0,          //折扣金额
//            'coupon_sn' =>  0,          //优惠券号
//            'supplierid'=>  0, 			//供应商id
        );

        $goodsService = new GoodsService();
        $goods_info = $goodsService->getGoodsSpec($spec_id,true);

        if(!$goods_info){
            return false;
        }

//        if($goods_info->is_set){
//            $subGoods = $goodsService->getSubGoods2([$goods_info->goods_id]);
//            foreach($subGoods as $k => $item){
//                $temp =[
//                    "goods_id" => $item->goods_id,
//                    "goods_name" => $item->goods_name,
//                    "spec_id" => $item->spec_id,
//                    "specification" => "",
//                    "price" => $item->price,
//                    "quantity" => $quantity,
//                    "goods_image" => "",
//                    "stock" => $item->stock,
//                    "sku" => $item->sku,
//                    "supplierid" => $item->supplierid
//                ];
//
//                $spec_1 = $item->spec_name_1 ? $item->spec_name_1 . ':' . $item->spec_1 : $item->spec_1;
//                $spec_2 = $item->spec_name_2 ? $item->spec_name_2 . ':' . $item->spec_2 : $item->spec_2;
//
//                if($item->spec_name_1 && $item->spec_name_2){
//                    $specification = $spec_1 . ' ' . $spec_2;
//                }else{
//                    $specification = '';
//                }
//
//                $temp['specification'] = $specification;
//
//                /* 商品缩略图 */
//                empty($item->default_image2) && $item->default_image2 = env('default_goods_image');
//                $temp['goods_image'] = complete_url($item->default_image2);
//
//                $return['items'][$k]        =   $temp;
//            }
//        }else{
            $temp =[
                "goods_id" => $goods_info->goods_id,
                "goods_name" => $goods_info->goods_name,
                "spec_id" => $goods_info->spec_id,
                "specification" => "",
                "price" => $goods_info->price,
                "market_price" => $goods_info->market_price,
                "quantity" => $quantity,
//                "goods_image" => $goods_info->default_image,
                "stock" => $goods_info->stock,
                "sku" => $goods_info->sku,
//                "supplierid" => $goods_info->supplierid
            ];

            $spec_1 = $goods_info->spec_name_1 ? $goods_info->spec_name_1 . ':' . $goods_info->spec_1 : $goods_info->spec_1;
            $spec_2 = $goods_info->spec_name_2 ? $goods_info->spec_name_2 . ':' . $goods_info->spec_2 : $goods_info->spec_2;

            if($goods_info->spec_name_1 && $goods_info->spec_name_2){
                $specification =  $spec_1 . ' ' . $spec_2;
            }elseif($goods_info->spec_name_1 && !$goods_info->spec_name_2 ){
                $specification =  $spec_1;
            }elseif($goods_info->spec_name_2 && !$goods_info->spec_name_1){
                $specification =  $spec_2;
            }else{
                $specification = "";
            }

            $temp['specification'] = $specification;

            /* 商品缩略图 */
            empty($goods_info->default_image) && $goods_info->default_image = env('default_goods_image');
            $temp['goods_image'] = complete_url($goods_info->default_image);

            $return['items'][]        =   $temp;
//        }

        $return['store_id']     =   $goods_info->store_id;
        $return['store_name']   =   $goods_info->store_name;
        $return['amount']   = $goods_info->price*$quantity;    //商品总价
        $return['type']         =   'material';
        $return['otype']        =   'normal';

        return $return;
    }

    /**
     *    立即购买商品信息
     *
     * @param   $spec_id 拼团规格id
     * @param   $quantity 商品数量
     * @param   $store_id 店铺id
     * @return    void
     */
    public function getPintuanGoodsInfo($extension,$spec_id,$quantity=1,$store_id=1)
    {
        $return = array(
            'items'     =>  array(),    //商品列表
            'quantity'  =>  $quantity,          //商品总量
            'amount'    =>  0,          //商品总价
//            'weight'   =>  0,
            'store_id'  =>  $store_id,          //所属店铺
            'store_name'=>  '',         //店铺名称
            'type'      =>  null,       //商品类型
            'otype'     =>  '',   //订单类型
            'allow_coupon'  => true,    //是否允许使用优惠券
            'discount'  =>  0,          //折扣金额
            'coupon_sn' =>  0,          //优惠券号
            'supplierid'=>  0, 			//供应商id
        );

        $pintuanService = new PintuanService();
        $goods_info = $pintuanService->getPintuanSpec($spec_id,true);

        if(!$goods_info){
            return false;
        }

        $temp =[
            "goods_id" => $goods_info->goods_id,
            "goods_name" => $goods_info->goods_name,
            "spec_id" => $goods_info->spec_id,
            "specification" => "",
            "price" => $goods_info->price,
            "quantity" => $quantity,
            "goods_image" => "",
            "stock" => $goods_info->stock,
            "sku" => $goods_info->sku,
            "supplierid" => $goods_info->supplierid
        ];

        $spec_1 = $goods_info->spec_name_1 ? $goods_info->spec_name_1 . ':' . $goods_info->spec_1 : $goods_info->spec_1;
        $spec_2 = $goods_info->spec_name_2 ? $goods_info->spec_name_2 . ':' . $goods_info->spec_2 : $goods_info->spec_2;

        if($goods_info->spec_name_1 && $goods_info->spec_name_2){
            $specification =  $spec_1 . ' ' . $spec_2;
        }elseif($goods_info->spec_name_1 && !$goods_info->spec_name_2 ){
            $specification =  $spec_1;
        }elseif($goods_info->spec_name_2 && !$goods_info->spec_name_1){
            $specification =  $spec_2;
        }else{
            $specification = "";
        }
        $temp['specification'] = $specification;

        /* 商品缩略图 */
        empty($goods_info->default_image2) && $goods_info->default_image2 = env('default_goods_image2');
        $temp['goods_image'] = complete_url($goods_info->default_image2);

        $return['items'][]        =   $temp;

        $return['store_id']     =   $goods_info->store_id;
        $return['store_name']   =   $goods_info->store_name;
        $return['amount']   = $goods_info->price*$quantity;    //商品总价
        $return['type']         =   'material';
        switch ($extension) {
            case PINTUAN_PUTONG:
                $return['otype']        =   'pintuan';
                break;
            case PINTUAN_MIAOSHA:
                $return['otype']        =   'miaosha';
                break;
            case PINTUAN_CHOUJIANG:
                $return['otype']        =   'choujiang';
                break;
        }

        return $return;
    }

    /**
     * 检查库存
     * @param $goods_items
     *
     */
    public function checkBeyondStock($goods_items)
    {
        $goods_beyond_stock = [];
        foreach ($goods_items as $rec_id => $goods)
        {
            if ($goods['quantity'] > $goods['stock'])
            {
                $goods_beyond_stock[$goods['spec_id']] = $goods;
            }
        }
        return $goods_beyond_stock;
    }

    /**
     *    生成订单号
     *
     *    @author    maqu
     *    @return    string
     */
    public function getOrderSn()
    {
        /*原规则 选择一个随机的方案*/
        mt_srand((double) microtime() * 1000000);
        $timestamp = gmtime();
        $y = date('Ymd', $timestamp);
        $z = date('z', $timestamp);
        $order_sn = 'G'.$y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        /* 订单号新规则 */
//        $order_sn=date('YmdHis',time());
        $orders = DB::table('order')->where('order_sn',$order_sn)->get();
        if (empty($orders))
        {
            /* 否则就使用这个订单号 */
            return $order_sn;
        }

        /* 如果有重复的，则重新生成 */
        return $this->getOrderSn();
    }

    /**
     *    提交生成订单，外部告诉我要下的单的商品类型及用户填写的表单数据以及商品数据，我生成好订单后返回订单ID
     *
     *    @param     array $data
                      array(
                        'goods_info'    =>  $goods_info,        //商品信息（包括列表，总价，总量，所属店铺，类型）,可靠的!
                        'post'          =>  Input::all(),       //用户填写的订单信息
                        'order_sn'      =>  $order_sn           //订单号
                       )
     *    @return    int
     */
    public function submitOrder($data) {
        try{
            /* 释放goods_info,post,order_sn三个变量 */
            extract($data);

            /* 处理订单基本信息 */
            $base_info = $this->handleOrderInfo($goods_info, $post);
            if (!$base_info)
            {
                /* 基本信息验证不通过 */
                $error='基本信息验证不通过';
                return array('order_id'=>0,'error'=>$error);
            }

            /* 处理订单收货人信息 */
            $consignee_info = $this->handleConsigneeInfo($goods_info, $post);
            if (!$consignee_info)
            {
                /* 收货人信息验证不通过 */
                $error='收货人信息验证不通过 ';
                return array('order_id'=>0,'error'=>$error);
            }

            /* 至此说明订单的信息都是可靠的，可以开始入库了 */
            /* 插入订单基本信息 */
            /* 获取店铺基本信息 */
            $store_info=DB::table('store')->where('store_id',$base_info['seller_id'])->first();
            if(!$store_info)
            {
                /* 店铺基本信息验证不通过 */
                $error='店铺基本信息验证不通过 ';
                return array('order_id'=>0,'error'=>$error);
            }

            $base_info['order_amount']  =   $base_info['goods_amount'] + $consignee_info['shipping_fee'] - $base_info['discount'];

            /* 如果优惠金额大于商品总额和运费的总和 */
            if ($base_info['order_amount'] <= 0)
            {
                $base_info['order_amount'] = 0;
                $base_info['discount'] = $base_info['goods_amount'] + $consignee_info['shipping_fee'];
                $base_info['status'] = ORDER_ACCEPTED;
                $base_info['pay_time'] = $base_info['add_time'];
            }
            $base_info['order_sn'] = $order_sn;
            $order_id =DB::table('order')->insertGetId($base_info);

            if (!$order_id)
            {
                /* 插入基本信息失败 */
                $error='插入基本信息失败 ';
                return array('order_id'=>0,'error'=>$error);
            }

            /* 插入收货人信息 */
            $consignee_info['order_id'] = $order_id;

            DB::table('order_extm')->insertGetId($consignee_info);
            /* 插入商品信息 */
            $goods_items = array();
            foreach ($goods_info['items'] as $key => $value)
            {
                $goods_items[] = array(
                    'order_id'      =>  $order_id,
                    'goods_id'      =>  $value['goods_id'],
                    'goods_name'    =>  $value['goods_name'],
                    'spec_id'       =>  $value['spec_id'],
                    'specification' =>  $value['specification'],
                    'market_price'  =>  $value['market_price'],
                    'price'         =>  $value['price'],
                    'quantity'      =>  $value['quantity'],
                    'goods_image'   =>  $value['goods_image'],
                    'sku'           =>  $value['sku'],
                );
            }
            DB::table('order_goods')->insert($goods_items);


    //         DB::table('order_goods')->insertGetId(addslashes_deep($goods_items));//防止二次注入
            return array('order_id'=>$order_id,'error'=>'');
        }
        catch(\Exception $e){
            throw $e;
        }
    }

    /**
     *    处理订单基本信息,返回有效的订单信息数组
     *
     *    @author    maqu
     *    @param     array $goods_info
     *    @param     array $post
     *    @return    array
     */
    private function handleOrderInfo($goods_info, $post)
    {
//        $items = $goods_info['items'];
//        $items = current($items);

        /* 默认都是待付款 */
        $order_status = ORDER_PENDING;
        /* 买家信息 */
        $user_id = $post['user_id'];
        $user = DB::table('member')->where('user_id',$user_id)->first();
        $user_name = $user->nickname;

        $extension = $goods_info['otype'];

        /* 返回基本信息 */
        return array(
//             'order_sn'      =>  $this->_gen_order_sn(),
            'type'          =>  $goods_info['type'],
            'extension'     =>  $extension,
            'seller_id'     =>  $goods_info['store_id'],
            'seller_name'   =>  addslashes($goods_info['store_name']),
            'buyer_id'      =>  $user_id,
            'buyer_name'    =>  addslashes($user_name),
            'buyer_email'   =>  $user->email,
            'status'        =>  $order_status,
            'add_time'      =>  gmtime(),
            'goods_amount'  =>  $goods_info['amount'],
            'discount'      =>  isset($goods_info['discount']) ? $goods_info['discount'] : 0,
//            'coupon_sn'		=> $goods_info['coupon_sn'],
//            'pay_time'		=> null,
//            'payment_id'	=> $post['payment_id'],
//            'tuan_id'       => $post['tuan_id'],
//            'pintuan_id'    => $post['pintuan_id'],
            'postscript'    => array_key_exists('postscript',$post) ? $post['postscript'] : '',
        );
    }

    /**
     *    处理收货人信息，返回有效的收货人信息
     *
     *    @author    Garbin
     *    @param     array $goods_info
     *    @param     array $post
     *    @return    array
     */
    private function handleConsigneeInfo($goods_info, $post)
    {
        /* 验证收货人信息填写是否完整 */
        $consignee_info = Address::find($post['addr_id']);
        if (!$consignee_info)
        {
            return false;
        }

//         /* 计算配送费用 */
//         $shipping_info = DB::table('shipping')->where('shipping_id',$post['shipping_id'])
//             ->where('store_id',$goods_info['store_id'])->where('enabled',1)->first();
//         if (empty($shipping_info))
//         {
//             return false;
//         }
//
//        /* 配送费用=首件费用＋超出的件数*续件费用 */
//        $shipping_fee = $shipping_info->first_price + ($goods_info['quantity'] - 1) * $shipping_info->step_price;

        /* 所有的拼团类的购买都是包邮的 */
//        if($goods_info['otype'] != 'normal'){
//            $shipping_fee = 0;
//        }else{
//            //获取店铺配置
//            $storeService = new StoreService();
//            $storeConfig = $storeService->getStoreConfig($goods_info['store_id']);
//
//            /* 配送费为固定设置 */
//            if($goods_info['amount'] < $storeConfig['shipping']['min_free']){
//                $shipping_fee = $storeConfig['shipping']['shipping_fee'];
//            }else{
//                $shipping_fee = 0;
//            }
//        }
        //根据地址与商品总量计算邮费
        $address= DB::table('address')->where('user_id',$post['user_id'])->where('addr_id',$post['addr_id'])->first();
        $arr_str=explode(" ",$address->region_name);//以空格为拆分条件
        if(!empty($arr_str))
        {
            $region_id =  DB::table('region')->where('region_name',$arr_str[0])->value('region_id');
        }
        $logisticsService = new LogisticsService();
        $postage = $logisticsService->getLogisticsMoney($goods_info['items'][0]['goods_id'],$region_id,$post['quantity']);;
        $shipping_fee = $postage['postage'];
        $postage['postage'];
        return array(
            'consignee'     =>  $consignee_info['consignee'],
            'region_id'     =>  $consignee_info['region_id'],
            'region_name'   =>  $consignee_info['region_name'],
            'address'       =>  $consignee_info['address'],
            'zipcode'       =>  $consignee_info['zipcode'],
            'phone_tel'     =>  $consignee_info['phone_tel'],
            'phone_mob'     =>  $consignee_info['phone_mob'],
//            'shipping_id'   =>  $shipping_info->shipping_id,
//            'shipping_name' =>  addslashes($shipping_info->shipping_name),
            'shipping_id'   =>  0,
            'shipping_name' =>  "",
            'shipping_fee'  =>  $shipping_fee,
        );
    }

    /**
     * 下单完成后清理商品
     *
     * @param   $user_id 用户id
     * @param   $rec_ids 购物车ids
     * @param   $goods  购物类型
     * @return    void
     */
    public function clearGoods($user_id,$rec_ids,$goods)
    {
        switch ($goods)
        {
            case 'groupbuy':
//                /* 团购的商品 */
//                $model_groupbuy =& m('groupbuy');
//                $model_groupbuy->updateRelation('be_join', $_GET['group_id'], $this->visitor->get('user_id'), array(
//                    'order_id'  => $order_id,
//                ));
                break;
            default://购物车中的商品
                if(count($rec_ids)>0){
                    DB::table('cart')->whereIn('rec_id',$rec_ids)->where('user_id',$user_id)
                        ->delete();
                }else{
                    DB::table('cart')->where('user_id',$user_id)
                        ->delete();
                }

                break;
        }
    }

    /**
     * 修改订单中商品的库存，可以是减少也可以是加回
     * @param string $type
     * @param $order_id
     * @param bool|true $withTrans
     */
    public function changeStock($type='-',$order_id,$withTrans = true)
    {
        /* 获取订单商品列表 */
        $ordergoods = DB::table('order_goods')
            ->where('order_id',$order_id)
            ->select('goods_id','rec_id', 'spec_id', 'quantity')->get();
        if($withTrans){
            DB::beginTransaction();
        }
        try{

            /* 依次改变库存 */
            foreach ($ordergoods as $goods)
            {
                if($type == '-'){
                    DB::table('goods_spec')
                        ->where('spec_id',$goods->spec_id)->decrement('stock',$goods->quantity);

                    DB::table('goods_statistics')
                        ->where('goods_id',$goods->goods_id)->increment('sales',$goods->quantity);
                }else{
                    DB::table('goods_spec')
                        ->where('spec_id',$goods->spec_id)->increment('stock',$goods->quantity);

                    DB::table('goods_statistics')
                        ->where('goods_id',$goods->goods_id)->decrement('sales',$goods->quantity);
                }

            }

            if($withTrans){
                DB::commit();
            }

        }catch (\Exception $e){
            Log::ERROR($e->getMessage());
            if($withTrans){
                DB::rollback();
            }
        }
    }

    /**
     *    加回订单中商品的库存
     *
     *    @author    shengl
     *    @param     String $extension  订单类型
     *    @param     int    $order_id   订单ID
     *    @param     int    $goods_id   商品ID
     *    @param     int    $pintuan_id 拼团id 默认0
     *    @return    bool
     */
    public function addStock($extension, $order_id,$goods_id,$pintuan_id = 0)
    {
        /* 获取订单商品列表 */
        $ordergoods = DB::table('order_goods')
            ->where('order_id',$order_id)
            ->where('goods_id',$goods_id)
            ->select('goods_id','rec_id', 'spec_id', 'quantity')->get();

        switch($extension){
            case 'normal':
                /* 依次改变库存 */
                foreach ($ordergoods as $goods)
                {
                    DB::table('goods_spec')
                        ->where('spec_id',$goods->spec_id)->increment('stock',$goods->quantity);
                }
                break;
            case 'pintuan':
                /* 依次改变库存 */
                foreach ($ordergoods as $goods)
                {
                    PintuanSpec::where('pintuan_id',$pintuan_id)
                        ->where('spec_id',$goods->spec_id)->increment('limit_count',$goods->quantity);

                    Pintuan::where('pintuan_id',$pintuan_id)->increment('limit_count',$goods->quantity);

                    DB::table('goods_spec')
                        ->where('spec_id',$goods->spec_id)->increment('stock',$goods->quantity);
                }
                break;
            case 'miaosha':
                /* 依次改变库存 */
                foreach ($ordergoods as $goods)
                {
                    PintuanSpec::where('pintuan_id',$pintuan_id)
                        ->where('spec_id',$goods->spec_id)->increment('limit_count',$goods->quantity);

                    Pintuan::where('pintuan_id',$pintuan_id)->increment('limit_count',$goods->quantity);

                    DB::table('goods_spec')
                        ->where('spec_id',$goods->spec_id)->increment('stock',$goods->quantity);
                }
                break;
            case 'choujiang':
                /* 依次改变库存 */
                foreach ($ordergoods as $goods)
                {
                    PintuanSpec::where('pintuan_id',$pintuan_id)
                        ->where('spec_id',$goods->spec_id)->increment('limit_count',$goods->quantity);

                    Pintuan::where('pintuan_id',$pintuan_id)->increment('limit_count',$goods->quantity);

                    DB::table('goods_spec')
                        ->where('spec_id',$goods->spec_id)->increment('stock',$goods->quantity);
                }
                break;
        }
    }

    /**
     * 获取订单列表
     *
     * @param $user_id 用户ID
     * @param String $nav 导航
     * @param int $firstrow         第一行
     * @param int $pagesize         每页条数
     * @return mixed
     */
    public function getOrderList($user_id,$nav="all",$firstrow=0,$pagesize=10){
        //获取订单列表数据
        $query = Order::where('buyer_id',$user_id)
            ->where("delflg_buyer",NO);

        if ($nav === 'pendding') {//待付款
            $status = ORDER_PENDING; //订单状态为待付款
            $query = $query->where ( 'order.status', $status );
        } elseif ($nav === 'accepted') {//待发货
            $status = ORDER_ACCEPTED; //订单状态为待发货
            $query = $query->where ( 'order.status', $status );
        } elseif ($nav === 'shipped') {//待收货
            $status = ORDER_SHIPPED; //订单状态为已发货
            $query = $query->where ( 'order.status', $status );
        }  elseif ($nav === 'waite_evaluate') {//待评价
            $status = ORDER_FINISHED;//订单状态为已完成
            $query = $query->where ( 'order.status', $status )
                ->where('evaluation_status',EVALUATE_WAIT);
        }elseif ($nav === 'finished') {
            $status = ORDER_FINISHED;//订单状态为已完成
            $query = $query->where ( 'order.status', $status )
                ->where('evaluation_status',EVALUATE_YES);
        }else{
            $status = TOUR_ORDER_AGREE;//卖家同意退款
        }
        
        //全部订单
        $user_orders = $query->orderBy('add_time','desc')->skip($firstrow)->take($pagesize)
            ->with('orderExtm','orderExtm.shipping','payment','orderGoods','orderRefund','refundGoods')->get()->toArray();
        return $user_orders;
    }

    /**
     * 获取用户每种导航的种订单的数量
     *
     * @param $user_id 用户id
     * @return array
     */
    public function allcountList($user_id){
        $count = [
            'all' => 0,
            'pendding' => 0,
            'shipped' => 0,
            'waite_evaluation' => 0,
            'finished' => 0
        ];
        //全部
        $count['all'] = $query =Order::where('buyer_id',$user_id)
            ->where("delflg_buyer",NO)->count();

        //pendding待付款
        $pendding = Order::where('buyer_id',$user_id)
            ->where('status', ORDER_PENDING)
            ->where("delflg_buyer",NO)->count();
        $count['pendding'] = $pendding;

//        $accepted =DB::table('order')->where('buyer_id',$user_id)->select()
//            ->where('status', ORDER_ACCEPTED)->count();
//        $count['accepted'] = $accepted;

        //shipped已发货，待收货
        $shipped = Order::where('buyer_id',$user_id)
            ->where('status', ORDER_SHIPPED)
            ->where("delflg_buyer",NO)->count();
        $count['shipped'] = $shipped;

        //waite_evaluation待评价
        $waiteeva = Order::where('buyer_id',$user_id)
            ->where('status' , ORDER_FINISHED)
            ->where('evaluation_status',EVALUATE_WAIT)
            ->where("delflg_buyer",NO)->count();
        $count['waite_evaluation'] = $waiteeva;

        //finished已完成
        $finished = Order::where('buyer_id',$user_id)
            ->where('status' , ORDER_FINISHED)
            ->where('evaluation_status',EVALUATE_YES)
            ->where("delflg_buyer",NO)->count();
        $count['finished'] = $finished;

        return $count;
    }

    /**
     *    获取订单状态相应的文字表述
     *
     *    @param     int $order_status  订单主状态
     *    @param     int $evaluation_status  评价状态
     *    @return    string
     */
    public function orderStatus($order_status,$evaluation_status=0,$complain_status=0,$order_id=0)
    {
        $lang_key = '';
        switch ($order_status)
        {
            case ORDER_PENDING:
                $lang_key = 'order_pending';
                break;
            case ORDER_ACCEPTED:
                $lang_key = 'order_accepted';
                break;
            case ORDER_SHIPPED:
                $lang_key = 'order_shipped';
                break;
            case ORDER_FINISHED:
               switch($complain_status){
                    case 0://未投诉
                        if($evaluation_status==0){
                            $lang_key = 'waite_evaluation';
                        }else{
                            $lang_key = 'order_finished';
                        }
                        break;
                    case 1;//已投诉
                        $order_complain_status = DB::table('complain')
                            ->where('order_id',$order_id)
                            ->where('product_type','goods')
                            ->value('judge_state');
                        if($order_complain_status==0){
                            $lang_key = 'waite_handle';//已投诉，待处理
                        }elseif($order_complain_status==1){
                            $lang_key = 'complain_handle';//已投诉，处理中
                        }elseif($order_complain_status==2){//处理成功
                            if($evaluation_status==0){
                                $lang_key = 'waite_evaluation';
                            }else{
                                $lang_key = 'order_finished';
                            }
                        }
                        break;
               }
                break;
            case ORDER_REFUND:
                $lang_key = 'order_refunded';
                break;
            case ORDER_REFUNDING:
                $lang_key = 'order_refunding';
                break;
            case TOUR_ORDER_AGREE:
                $lang_key = 'order_agree';
                break;
            case ORDER_CANCELED:
                $lang_key = 'order_canceled';
                break;
            case ORDER_DELETED:
                $lang_key = 'order_deleted';
        }

        $keyvalues = array(
            'waite_handle'     => '已投诉，待处理',
            'complain_handle'     => '投诉处理中',
            'order_pending'     => '待付款',
            'order_accepted'   => '待发货',
            'order_shipped'     => '已发货',
            'order_canceled'    => '已取消',
            'order_refunded'	=> '已退款',
            'order_refunding'	=> '等待卖家审核',
            'order_finished'    => '已完成',
            'order_deleted'		=> '已删除',
            'waite_evaluation'  => '待评价',
            'order_agree'  => '卖家同意退款');

        return $lang_key  ? $keyvalues[$lang_key] : $lang_key;
    }

    /**
     *    获取订单状态相应的详细表述
     *
     *    @param     int $order_status  订单主状态
     *    @param     int $ship_time  发货时间
     *    @param     int $tuan_id  团id
     *    @return    string
     */
    public function orderStatusDetail($order_status,$ship_time=0,$tuan_id=0,$extension='normal')
    {
        $lang_key = '';
        switch ($order_status)
        {
            case ORDER_PENDING:
                $lang_key = 'order_pending';
                break;
            case ORDER_ACCEPTED:
                if($tuan_id >0){
                    $lang_key = 'order_waite';
                    if($extension == 'choujiang'){
                        $lang_key = 'order_waite2';
                    }
                }else{
                    $lang_key = 'order_accepted';
                }
                break;
            case ORDER_SHIPPED:
                $lang_key = 'order_shipped';
                break;
            case ORDER_FINISHED:
                $lang_key = 'order_finished';
                break;
            case ORDER_REFUND:
                $lang_key = 'order_refunded';
                break;
            case ORDER_CANCELED:
                $lang_key = 'order_canceled';
                break;
            case TOUR_ORDER_AGREE:
                $lang_key = 'order_agree';
                break;
            case ORDER_DELETED:
                $lang_key = 'order_deleted';
        }

        $rest = '';
        if($ship_time > 0){
            $confim_time = DB::table('config')->where('code','order_info_confirm')->value('value');
            $rest_time = $ship_time+$confim_time*24*60*60 -gmtime();
            $rest = "，还剩".$this->_time2string($rest_time)."自动确认";
        }

        $keyvalues = array(
            'order_pending'     => '交易尚未开始，您还未付款',
            'order_waite'       => '将在组团成功后尽快为您包装及发货',
            'order_waite2'      => '将在开奖后尽快为您包装及发货',
            'order_accepted'    => '将尽快为您包装及发货',
            'order_shipped'     => '打包完毕'.$rest,
            'order_canceled'    => '该笔订单已取消',
            'order_refunded'	=> '该笔订单已完全退款',
            'order_finished'    => '交易完成',
            'order_deleted'		=> '该笔订单已删除',
             'order_agree' =>  '等待退款金额到账');

        return $lang_key  ? $keyvalues[$lang_key] : $lang_key;
    }

    /**
     *    获取订单状态相应的文字表述
     *
     *    @param     int $refund_type  退款类型 1->退款 2->退货 0->无
     *    @param     int $refund_status  退款/货状态
     *    @return    string
     */
    public function orderGoodsStatus($refund_type=0,$refund_status=0)
    {
        $lang_key = '';
        switch ($refund_type)
        {
            case REFUND_TYPE_REFUND:
                switch ($refund_status)
                {
                    case REFUND_PENDING://等待卖家同意退款
                        $lang_key = 'refund_pending_1';
                        break;
                    case REFUND_REFUNDING:// 退款中
                        $lang_key = 'refund_refunding';
                        break;
                    case REFUND_FINISHED:// 退款成功
                        $lang_key = 'refund_finished_1';
                        break;
                    case REFUND_CANCELED:// 退款已取消

                        break;
                }
                break;
            case REFUND_TYPE_RETURN_GOODS:
                switch ($refund_status)
                {
                    case REFUND_PENDING://等待卖家同意退货
                        $lang_key = 'refund_pending_2';
                        break;
                    case REFUND_ACCEPTED:// 卖家已审核，等待买家发货
                        $lang_key = 'refund_accepted';
                        break;
                    case REFUND_SHIPPED:// 买家已发货
                        $lang_key = 'refund_shipped';
                        break;
                    case REFUND_REFUNDING:// 退款中
                        $lang_key = 'refund_refunding';
                        break;
                    case REFUND_FINISHED:// 退货成功
                        $lang_key = 'refund_finished_2';
                        break;
                    case REFUND_CANCELED:// 退货已取消

                        break;
                }
                break;
            default :;
        }

        $keyvalues = array(
            'refund_pending_1'   => '已申请退款',
            'refund_pending_2'     => '已申请退货',
            'refund_accepted'     => '等待买家退货',
            'refund_shipped'    => '等待卖家收货',
            'refund_refunding'   => '退款中',
            'refund_finished_1'	=> '退款成功',
            'refund_finished_2'    => '退货成功');

        return $lang_key  ? $keyvalues[$lang_key] : $lang_key;
    }

    /**
     *    订单操作管理
     *
     *    @param     int $order  订单
     *    @return    array
     */
    public function orderIcan($order){
        $order_status =$order['status'];
        $evaluation_status=$order['evaluation_status'];
        $complain_status = $order['complain_status'];

        $order_ican=array(
            'payment'		=> false,//付款
            'cancel' 	=> false,//取消订单
            'delete'    => false,//删除订单（逻辑）
            'confirm_order' => false,//收货
            'refound'		=> false,//退款
            'cancel_refound'	=> false,//取消退款
            'complain'	=> false,//投诉
            'view_logistics' => false,//查看物流
            'evaluate'		=> false,//评价
        );

        if(!$order){
            return $order_ican;
        }

        //订单相关动作
        if($order_status == ORDER_CANCELED || $order_status == ORDER_REFUND || $order_status == ORDER_FINISHED) {
            $order_ican['delete'] = true;
        }

        if($order_status ==ORDER_PENDING){//11：等待付款
            $order_ican['cancel'] = true;
            $order_ican['payment'] = true;
        }else if($order_status ==ORDER_SHIPPED){//30：已发货，等待收货
            if($complain_status == 0){
             $order_ican['complain'] = true;
            }
            $order_ican['confirm_order'] = true;
            $order_ican['refound'] = true;
        }else if($order_status ==ORDER_ACCEPTED){//20：待发货，可退款/退货
            $order_ican['refound'] = true;
        }else if($order_status ==ORDER_REFUNDING){//21：用户申请退款，可取消
            $order_ican['cancel_refound'] = true;
        }else if($order_status ==ORDER_FINISHED){//40：交易完成
            if($evaluation_status == 0){
                $order_ican['evaluate'] = true;
            }
            if($complain_status == 0){
                $order_ican['complain'] = true;
            }
            $order_ican['delete'] = true;
        }

        //查看物流
        $order_ican['view_logistics'] = $order['invoice_no']?true:false;

        return $order_ican;
    }

    /**
     * 订单商品操作管理
     * @param $extension 订单类型
     * @param $order_status 订单状态
     * @param $goods_status 商品状态
     */
    public function orderGoodsIcan($extension,$order_status,$goods_status=0){
        $ordergoods_ican=array(
            'apply_refund' 	=> false,//商品退款申请
            'cancel_refund' => false,//取消退款申请
            'return_goods'	=> false,//退货
            'change_expressno' => false,//修改退货单号
        );

        if($extension != 'normal'){//如果不是普通订单
            return $ordergoods_ican;
        }

        //只有已付款并且交易为完成的订单可以申请退款
        if($order_status ==ORDER_ACCEPTED
            || $order_status ==ORDER_SHIPPED){
            if($goods_status  == 0){//0 表示初始状态
                $ordergoods_ican['apply_refund'] = true;
            } else if($goods_status == REFUND_PENDING){//10：退款申请中
                $ordergoods_ican['cancel_refund'] = true;
            } else if($goods_status == REFUND_ACCEPTED){//20：申请通过，等待买家退货
                $ordergoods_ican['return_goods'] = true;
            } else if($goods_status == REFUND_SHIPPED){//30：买家已经发货
                $ordergoods_ican['change_expressno'] = true;
            }
        }
        return $ordergoods_ican;
    }

    /**
     * 获取订单详情
     *
     * @param $user_id 用户ID
     * @param int $order_id 订单id
     * @return mixed
     */
    public function getOrderInfo($user_id,$order_id){
        //获取订单列表数据
        $query = Order::where('order_id',$order_id)
            ->where('buyer_id',$user_id)
            ->where("delflg_buyer",NO);

        $user_orders = $query->with('orderExtm','orderExtm.shipping','payment','orderGoods','orderGoods.goodsSpec','orderRefund','refundGoods')->first();
        return $user_orders;
    }

    /**
     * 添加订单操作日志
     * @param $order_id 订单id
     * @param $user_name 操作者用户名
     * @param $old_status 订单原先状态
     * @param $new_status 操作后的订单撞他
     * @param $remark 操作原因
     * @param bool/false $withTrans 是否单独开启事务
     */
    public function addOrderLog($order_id,$user_name,$old_status,$new_status,$remark,$withTrans=true){
        if($withTrans){
            DB::beginTransaction();
        }
        try {
            DB::table('order_log')->insert(array(
                'order_id' => $order_id,
                'operator' => addslashes($user_name),
                'order_status' => $this->orderStatus($old_status),
                'changed_status' => $this->orderStatus($new_status),
                'remark' => $remark,
                'log_time' => gmtime(),
            ));
            if($withTrans){
                DB::commit();
            }
        }catch (\Exception $e){
            Log::ERROR($e->getMessage());
            if($withTrans){
                DB::rollback();
            }
        }
    }

    /**
     * 获取订单商品详情
     *
     * @param $user_id 用户ID
     * @param int $rec_id 订单商品id
     * @return mixed
     */
    public function getOrderGoodsInfo($rec_id){
        //获取订单列表数据
        $query = OrderGoods::where('rec_id',$rec_id);

        $orderGoods = $query->first();

        return $orderGoods;
    }

    public function check_rest_time($ship_time,$store_id = 1){

        $storeService = new StoreService();
        $storeConfig = $storeService->getStoreConfig($store_id);

        $rest = $ship_time+$storeConfig['auto_confirm_days']*24*60*60 -gmtime();

        return date('d天H小时',$rest);
    }

    public function complainGoodsOrder($user_id,$order_id,$link_name,$link_phone,$comment,$complain_images,$type,$withTrans = true){
        //买家用户信息
        $userInfo = User::find($user_id);


        $OrderInfo = self::getOrderInfo($user_id,$order_id);

        if(!$OrderInfo){
            return $this->failure('该订单存在数据异常，不可投诉');
        }

        if($OrderInfo->status != ORDER_FINISHED && $OrderInfo->status != ORDER_SHIPPED){
            return $this->failure("该订单尚未发货，不可投诉");
        }

        if($OrderInfo->complain_status == COMPLAIN_YES){
            return $this->failure("该订单已投诉过，请联系客服查询进度");
        }

        if($withTrans){
            DB::beginTransaction();
        }
        try {
            $OrderInfo->complain_status = COMPLAIN_YES;
            $OrderInfo->complain_time = gmtime();

            /* 更新订单状态 */
            $OrderInfo->save();
            $goods_id = $OrderInfo->OrderGoods->toArray();
            $OrderComplain = new OrderComplain();
            $OrderComplain->item_id = $goods_id[0]['goods_id'];
            $OrderComplain->order_id = $OrderInfo->order_id;
            $OrderComplain->user_id = $OrderInfo->buyer_id;
            $OrderComplain->store_id = $OrderInfo->seller_id;
            $OrderComplain->product_type = $type;
            $OrderComplain->link_name = $link_name;
            $OrderComplain->link_phone = $link_phone;
            $OrderComplain->desc = $comment;
            $OrderComplain->pictures = json_encode($complain_images);
            $OrderComplain->create_at = gmtime();
            $OrderComplain->save();

            /* 添加订单操作日志 订单从交易完成到提交投诉信息 */
            $old_status = '交易完成';
            $new_status = '已提交投诉信息';
            self::addOrderLog($order_id,$userInfo->nickname,$old_status,$new_status,"买家投诉订单");

            if($withTrans){
                DB::commit();
            }
            return $this->success();

        } catch (\Exception $e) {
            if($withTrans){
                DB::rollback();
            }
            Log::ERROR($e->getMessage());
            return $this->failure('处理错误，暂时无法投诉');
        }
    }

    function _time2string($second){
        $day = floor($second/(3600*24));
        $second = $second%(3600*24);//除去整天之后剩余的时间
        $hour = floor($second/3600);
        $second = $second%3600;//除去整小时之后剩余的时间
        $minute = floor($second/60);
        $second = $second%60;//除去整分钟之后剩余的时间
        //返回字符串
        return $day.'天'.$hour.'小时'.$minute.'分'.$second.'秒';
    }

}
